const jwt = require("jsonwebtoken");

const secretKey = "node-books";

//创建token
const sign = (data) => {
  return jwt.sign(data, secretKey, {
    expiresIn: 60 * 60 * 24,
  });
};

//效验token中间件

const authToken = (req, res, next) => {
  const token = req.headers["token"];
  if (!token) return res.status(401).send({ message: "请提供token" });
  jwt.verify(token, secretKey, (error, data) => {
    if (error) return res.status(401).send({ message: "token已过期" });
    next();
  });
};

module.exports = { sign, authToken };
